package com.ruoyi.invoice.controller;

import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.invoice.domain.vo.InvoiceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.invoice.domain.Invoice;
import com.ruoyi.invoice.service.IInvoiceService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 销项发票Controller
 * 
 * @author XU
 * @date 2025-03-13
 */
@RestController
@RequestMapping("/invoice")
@Slf4j
public class InvoiceController extends BaseController
{
    @Autowired
    private IInvoiceService invoiceService;

    /**
     * 查询销项发票列表
     */
    @RequiresPermissions("invoice:invoice:list")
    @GetMapping("/list")
    public TableDataInfo list(InvoiceVO invoiceVO)
    {
        startPage();
        List<InvoiceVO> list = invoiceService.selectInvoiceList(invoiceVO);
        return getDataTable(list);
    }


    @Bean
    public ThreadPoolTaskExecutor exportThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(20);
        executor.setThreadNamePrefix("export-thread-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 导出销项发票列表
     */
    @RequiresPermissions("invoice:invoice:export")
    @Log(title = "销项发票", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody InvoiceVO invoiceVO) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = java.net.URLEncoder.encode("销项发票数据_" + System.currentTimeMillis() + ".xlsx", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setHeader("Access-Control-Expose-Headers", "*");

            List<InvoiceVO> allData = invoiceService.selectInvoiceList(invoiceVO);
            int chunkSize = allData.size() / 5; // 假设分成 5 个线程处理
            List<List<InvoiceVO>> chunks = new ArrayList<>();
            for (int i = 0; i < allData.size(); i += chunkSize) {
                chunks.add(allData.subList(i, Math.min(i + chunkSize, allData.size())));
            }

            List<CompletableFuture<Void>> futures = new ArrayList<>();
            for (List<InvoiceVO> chunk : chunks) {
                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                    try {
                        ExcelUtil<InvoiceVO> util = new ExcelUtil<>(InvoiceVO.class);
                        util.exportExcel(response, chunk, "销项发票数据");
                    } catch (Exception e) {
                        log.error("导出销项发票失败", e);
                        handleExportError(response, e.getMessage());
                    }
                }, exportThreadPool());
                futures.add(future);
            }

            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        } catch (Exception e) {
            log.error("导出销项发票失败", e);
            handleExportError(response, e.getMessage());
        }
    }

    /**
     * 处理导出错误
     */
    private void handleExportError(HttpServletResponse response, String errorMessage) {
        try {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println("{\"code\":500,\"msg\":\"" + errorMessage + "\"}");
        } catch (IOException ex) {
            log.error("写入错误响应失败", ex);
        }
    }


    /**
     * 获取销项发票详细信息
     */
    @RequiresPermissions("invoice:invoice:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(invoiceService.selectInvoiceById(id));
    }

    /**
     * 新增销项发票
     */
    @RequiresPermissions("invoice:invoice:add")
    @Log(title = "销项发票", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Invoice invoice)
    {
        return toAjax(invoiceService.insertInvoice(invoice));
    }
    /**
     * 修改销项发票
     */
    @RequiresPermissions("invoice:invoice:edit")
    @Log(title = "销项发票", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Invoice invoice)
    {
        return toAjax(invoiceService.updateInvoice(invoice));
    }

    /**
     * 删除销项发票
     */
    @RequiresPermissions("invoice:invoice:remove")
    @Log(title = "销项发票", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(invoiceService.deleteInvoiceByIds(ids));
    }


}
